package com.bjpowernode.crm.web.controller;

import com.bjpowernode.crm.pojo.User;
import com.bjpowernode.crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/*创建该类的作用：使得html的访问都转化为jsp页面的跳转，使得页面引用页面有效*/
@Controller
public class CommonsController {

    @Resource
    private UserService userService;

    @RequestMapping("/**/*.html")
    public String pager(HttpServletRequest request) {
        // /xxx/xxx.html
        String uri = request.getRequestURI();
        System.out.println(uri);
        // "/xxx/xxx.html" ===> "/xxx/xxx"
        String viewName = uri.substring(1, uri.lastIndexOf("."));
        return viewName;
    }



    //十天免登陆的功能请求：因为我们存入客户端的密码已经加密了，所以我们只能再次另立请求
    //再次另立请求数据库，直接传入客户端已经加密了的密码与数据库密码对应，这样才能确保密码正确
    @RequestMapping("/")
    public String selectLoginAuto(@CookieValue(value = "loginAct",required = false) String loginAct,
                                  @CookieValue(value = "loginPwd",required = false) String loginPwd,
                                  HttpServletRequest request){

        if((loginAct!=null && !loginAct.equals(""))&&(loginPwd!=null&& !"".equals(loginPwd))){
            //获取ip地址：
            String remoteAddr = request.getRemoteAddr();
            User user = userService.selectLoginAuto(loginAct, loginPwd, remoteAddr);
            if(user!=null){
                //将用户存在session中，做登录证明
                request.getSession().setAttribute("loginUser", user);
                return "redirect:/workbench/index.html";
            }
        }

        return "index";
    }
}
